"""
错误处理中间件 - 统一异常处理
"""

import logging
import traceback
from flask import Flask, request, jsonify
from werkzeug.exceptions import HTTPException

from .response_formatter import ResponseFormatter


logger = logging.getLogger(__name__)


class ErrorHandler:
    """统一错误处理器"""
    
    def __init__(self, app: Flask = None):
        self.app = app
        if app is not None:
            self.init_app(app)
    
    def init_app(self, app: Flask):
        """初始化错误处理"""
        self.app = app
        
        # 注册全局异常处理器
        app.register_error_handler(Exception, self.handle_general_exception)
        app.register_error_handler(HTTPException, self.handle_http_exception)
        app.register_error_handler(404, self.handle_not_found)
        app.register_error_handler(500, self.handle_internal_error)
    
    def handle_general_exception(self, e: Exception):
        """处理一般异常"""
        logger.error(f"未处理的异常: {str(e)}")
        logger.error(f"请求路径: {request.path}")
        logger.error(f"请求方法: {request.method}")
        logger.error(f"异常详情: {traceback.format_exc()}")
        
        return ResponseFormatter.error(
            message="服务器内部错误",
            error_code="INTERNAL_ERROR",
            status_code=500
        )
    
    def handle_http_exception(self, e: HTTPException):
        """处理HTTP异常"""
        logger.warning(f"HTTP异常: {e.code} - {e.description}")
        
        return ResponseFormatter.error(
            message=e.description or "HTTP错误",
            error_code=f"HTTP_{e.code}",
            status_code=e.code
        )
    
    def handle_not_found(self, e):
        """处理404错误"""
        return ResponseFormatter.error(
            message="请求的资源不存在",
            error_code="NOT_FOUND",
            status_code=404
        )
    
    def handle_internal_error(self, e):
        """处理500错误"""
        logger.error(f"内部服务器错误: {str(e)}")
        logger.error(f"异常详情: {traceback.format_exc()}")
        
        return ResponseFormatter.error(
            message="内部服务器错误",
            error_code="INTERNAL_SERVER_ERROR", 
            status_code=500
        )


def setup_error_handlers(app: Flask):
    """设置错误处理器的便捷函数"""
    ErrorHandler(app)
    logger.info("错误处理器设置完成")